package xuan.gui;

import javax.swing.JFileChooser;

import javax.swing.JFrame;
import javax.swing.JMenuBar;
import javax.swing.JMenu;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;


@SuppressWarnings("serial")
public class DemoMain extends JFrame implements ActionListener{	
	
	private JMenuItem mnOpen = new JMenuItem("open");;
	private JMenuItem mnSave = new JMenuItem("save");
	private JMenuItem mnQuit = new JMenuItem("quit");
	private final JMenuItem mnReload = new JMenuItem("reload");
	private InteractiveMergePanel interactiveMergePanel =null;
	
	public DemoMain(String[] args) {
		
		interactiveMergePanel = new InteractiveMergePanel(args);
		getContentPane().add(interactiveMergePanel, "Center");
		
		JMenuBar menuBar = new JMenuBar();
		setJMenuBar(menuBar);
		
		JMenu mnFiles = new JMenu("File");
		menuBar.add(mnFiles);
	
		mnFiles.add(mnOpen);
		mnOpen.addActionListener(this);
		
		mnFiles.add(mnSave);
		mnSave.addActionListener(this);
		
		mnFiles.add(mnReload);
		mnReload.addActionListener(this);
		
		mnFiles.add(mnQuit);
		mnQuit.addActionListener(this);
		
		JMenu menu = new JMenu("?");
		menuBar.add(menu);
			
		pack();
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		setTitle("Interactive merge");
		setLocationRelativeTo(null);
		setVisible(true);
	}
	
	public void actionPerformed(ActionEvent e) {
		Object eSource = e.getSource();
	    if (eSource == mnOpen) {
	    	OpenFileWindow openFileWindow = new OpenFileWindow(this);
	        Transfer transfer = new Transfer();
	    	if (openFileWindow.showDialog(transfer)) {	    		
	    		interactiveMergePanel.load(transfer.getValue());
	    	}
	    }
	    if(eSource == mnSave){
	    	JFileChooser chooser = new JFileChooser();
	    	chooser.showSaveDialog(this);
	    	try{
				String fileName = chooser.getSelectedFile().getAbsolutePath();
				interactiveMergePanel.save(fileName);
				JOptionPane.showMessageDialog(this, "file is successfully saved");
			}
			catch(Exception ex){
				JOptionPane.showMessageDialog(this, "file is not successfully saved");
			}
	    }
	    if(eSource == mnReload){
	    	interactiveMergePanel.removeAll();	    		
	    	interactiveMergePanel.reload();
	    }
	    if(eSource == mnQuit){ 
	    	System.exit(0);
	    }
	}
	
	public static void main(String[] args) {
		new DemoMain(args);	    
	}
}
